tar xf ${DOWNLOADDIR}/Python-3.13.7.tar.xz -C ${BUILDDIR}
pushd ${BUILDDIR}/Python-3.13.7
    cat > config.cache << "EOF"
    ac_cv_aligned_required=no
    ac_cv_broken_sem_getvalue=no
    ac_cv_computed_gotos=yes
    ac_cv_pthread_is_default=yes
    ac_cv_pthread_system_supported=yes
    ac_cv_working_tzset=yes
    ac_cv_buggy_getaddrinfo=no
    ac_cv_file__dev_ptmx=yes
    ac_cv_file__dev_ptc=no
EOF
	./configure --prefix=/usr  --libdir=/usr/lib64 \
	            --build=${CROSS_HOST} --host=${CROSS_TARGET} --enable-shared \
	            --with-system-expat --with-build-python=python3 --with-ensurepip=install \
	            --with-platlibdir=lib64 \
	            --cache-file=config.cache
	make ${JOBS}
	make DESTDIR=${SYSDIR}/sysroot install
popd
ln -sv python3 ${SYSDIR}/sysroot/usr/bin/python

cp ${SYSDIR}/sysroot/usr/lib64/python3.13/_sysconfigdata__linux_loongarch64-linux-gnu.py ${SYSDIR}/cross-tools/lib64/python3.13/_sysconfigdata__linux_${CROSS_TARGET}.py
sed -i "/'INCLUDEPY'/s@'/usr/include@'${SYSDIR}/sysroot/usr/include@g" ${SYSDIR}/cross-tools/lib64/python3.13/_sysconfigdata__linux_${CROSS_TARGET}.py

sed -i -e "s@${SYSDIR}/sysroot@@g" \
       -e "s@${CROSS_TARGET}-@@g" \
       ${SYSDIR}/sysroot/usr/lib64/python3.13/_sysconfigdata__linux_loongarch64-linux-gnu.py

cp -v ${SYSDIR}/cross-tools/bin/python3.13-config{,.tools}
cp -v ${SYSDIR}/sysroot/usr/bin/python3.13-config ${SYSDIR}/cross-tools/bin/
sed -i "/prefix_real/s@=.*@=${SYSDIR}/sysroot/usr@g" ${SYSDIR}/cross-tools/bin/python3.13-config

echo "#!/bin/bash -e
if [ -f ${SYSDIR}/sysroot/usr/bin/python3 ]; then
    qemu-loongarch64 ${SYSDIR}/sysroot/usr/bin/python3 \"\$@\"
else
    _PYTHON_SYSCONFIGDATA_NAME=_sysconfigdata__linux_${CROSS_TARGET} ${SYSDIR}/cross-tools/bin/python3 \"\$@\"
fi" > ${SYSDIR}/cross-tools/bin/${CROSS_TARGET}-python3
chmod +x ${SYSDIR}/cross-tools/bin/${CROSS_TARGET}-python3
